package com.zhf.controller;

import com.github.pagehelper.PageInfo;
import com.zhf.domain.PromotionAd;
import com.zhf.domain.PromotionAdVO;
import com.zhf.domain.ResponseResult;
import com.zhf.service.PromotionAdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/12/4 21:21
 */
@RestController
@RequestMapping("/PromotionAd")
public class PromotionAdController {

    @Autowired
    private PromotionAdService promotionAdService;

    @RequestMapping("/findAllPromotionAdByPage")
    public ResponseResult findAllAdByPage(PromotionAdVO promotionAdVO){
        PageInfo<PromotionAd> adByPage = promotionAdService.findAllPromotionAdByPage(promotionAdVO);

        ResponseResult result = new ResponseResult(true, 200, "广告分页查询成功", adByPage);
        return result;
    }

    /*
     图片上传
     */
    @RequestMapping("/PromotionAdUpload")
    public ResponseResult fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        //判断接收到的上传文件是否为空
        if (file.isEmpty()){
            throw new RuntimeException();
        }
        //获取项目的部署路径
        String realPath = request.getServletContext().getRealPath("/");
        String ssm_web = realPath.substring(0, realPath.indexOf("ssm-web"));

        //获取源文件名
        String filename = file.getOriginalFilename();

        //生成新文件名
        String newFileName = System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));

        //文件上传
        String uploadPath=ssm_web+"upload\\";
        File filePath = new File(uploadPath, newFileName);
        //如果不存在则创建目录
        if(!filePath.getParentFile().exists()){
            filePath.getParentFile().mkdirs();
            System.out.println("创建目录："+filePath);
        }
        //图片上传
        file.transferTo(filePath);

        //将文件名和文件路径返回，进行响应
        HashMap<String, String> map = new HashMap<>();
        map.put("fileName", newFileName);
        map.put("filePath","http://localhost:8080/upload/"+newFileName);
        ResponseResult result = new ResponseResult(true, 200, "图片上传成功", map);
        return result;
    }

    /*
    广告动态上下线
     */
    @RequestMapping("/updatePromotionAdStatus")
    public ResponseResult updatePromotionStatus(int id,int status){
        promotionAdService.updatePromotionAdStatus(id, status);
        HashMap<String, Integer> map = new HashMap<>();
        map.put("status", status);
        ResponseResult result = new ResponseResult(true, 200, "响应成功", map);
        return result;
    }

}
